
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:massagist/manager/file_manager.dart';
import 'package:massagist/manager/request.dart';
import 'package:massagist/models/web_info_model_entity.dart';
import 'package:massagist/views/mass_appbar.dart';
import 'package:massagist/views/mass_grid_item.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../generated/l10n.dart';
import '../manager/config.dart';
import '../models/massage_model_entity.dart';

class MassagePage extends StatefulWidget {
  @override
  State<MassagePage> createState() => MassagePageState();
}

class MassagePageState extends State<MassagePage> {
  List<MassageModelEntity> massages = [];
  late WebViewController controller;
  String webTitle = S.current.TAB_MASSAGE_TEXT;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    initRequest();
  }

  Future<void> initRequest() async {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..addJavaScriptChannel('startFunction', onMessageReceived: (message) {
        try {
          // var responseString = Config.convertToJsonStringQuotes(raw: message.message);
          var responseInfo = WebInfoModelEntity.fromJson(json.decode(message.message));
          if (int.parse(responseInfo.type) == IN_WEB_JUMP) {
            controller.loadRequest(Uri.parse(responseInfo.url));
          } else if (int.parse(responseInfo.type) == OUT_WEB_JUMP) {
            opepOutUrl(responseInfo.url);
          }
        } catch (e) {
          print (e.toString());
        }
      })
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) async {
            var title = await controller.getTitle();
            if (Config.isNull(title!))
              title = S.current.TAB_MASSAGE_TEXT;

            setState(() {
              webTitle = title!;
            });
          },
          onWebResourceError: (WebResourceError error) {},
        ),
      )
      ..loadRequest(Uri.parse(Config.massageUrl));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: Container(
            child: GestureDetector(
              child: Icon(Icons.chevron_left_sharp, size: 40.sp, color: Color(0xFF1A1A1A),),
              onTap: () async {

                if (await controller.canGoBack()) {
                  controller.goBack();
                }
              },
            ),
          ),
          backgroundColor: Colors.white,
          title: Text(webTitle, style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
              color: Color(0xFF1A1A1A)
          ),),
          elevation: 0,
        ),
        body: WebViewWidget(controller: controller)
    );
  }

  Future<void> opepOutUrl(String web) async {
    final Uri url = Uri.parse(web);
    if (await canLaunchUrl(url)) {
      print (web);
      await launchUrl(url);
    } else {
      // throw 'Could not launch $url';
      print ("跳转失败");
    }
  }
}